import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/common_util/num_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/widgets/empty_view/h_empty_view.dart';
import 'package:star_author/widgets/empty_view/v_empty_view.dart';
import 'package:provider/provider.dart';

class CommentListItemWidget extends StatelessWidget {
  late bool? best;
  late Map<String, dynamic> item;
  late String status;
  late bool isEvaluated;
  late bool isMine;
  late String rateForDeducting;
  late String tenderPrice;
  List highlightStatus = ['waitconfirm', 'evaluation', 'wait_pay', 'finished'];
  List grayStatus = ['onsale'];
  int index;

  CommentListItemWidget({
    Key? key,
    this.best,
    this.index: 0,
    required this.item,
    required this.status,
    required this.isEvaluated,
    required this.rateForDeducting,
    required this.isMine,
    required this.tenderPrice,
  }) : super(key: key);

  Widget renderPrice(
    String? donePrice,
    String? price,
    mi,
  ) {
    Color color = UIConstant.color33;
    if (!checkValid()) {
      color = UIConstant.color99;
    } else {
      if (highlightStatus.contains(status)) {
        color = ColorConf.orange;
      } else if (grayStatus.contains(status)) {
        color = UIConstant.color33;
      }
    }

    return RichText(
      text: TextSpan(
        style: TextStyle(
          color: color,
        ),
        children: [
          TextSpan(
            text: '￥',
            style: TextStyle(fontSize: 12.sp, fontWeight: FontWeight.bold),
          ),
          TextSpan(
            text: formatPrice(!(['0', 0, '', null].contains(tenderPrice))
                ? price
                : getImmediatePrice(rateForDeducting, item['price'])),
            style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
          )
        ],
      ),
    );
  }

  /// 计算天数、小时、分钟、秒
  String caculateTime(nowTime, endTime) {
    var _surplus = endTime.difference(nowTime);
    int day = (_surplus.inSeconds ~/ 3600) ~/ 24;
    int hour = (_surplus.inSeconds ~/ 3600) % 24;
    int minute = _surplus.inSeconds % 3600 ~/ 60;
    int second = _surplus.inSeconds % 60;

    var str = '';
    if (day > 30) {
      return formatDate(nowTime.toString(), format: "yyyy-MM-dd");
    } else {
      if (day > 0) {
        str = day.toString() + '天';
      } else if (hour > 0) {
        str = str + hour.toString() + '小时';
      } else if (minute > 0) {
        str = str + minute.toString() + '分钟';
      } else if (second < 60) {
        // str = str + second.toString() + '秒';
        return "刚刚";
      }
    }
    return str + "前";
  }

  bool checkValid() {
    if (!isMine && ['evaluation'].contains(status)) {
      return true;
    } else {
      return (item['is_valid'] ?? false);
    }
  }

  @override
  Widget build(BuildContext context) {
    String? id = item['owner']['id'].toString();
    String? photo = item['owner']['avatar'];
    String? rate_of_invalid_tenders =
        item['owner']['rate_of_invalid_tenders'] ?? "";
    String? name = item['owner']['nickname'];
    String? level = item['owner']['level'].toString();
    String? donePrice = item['done_price'];
    String? price = item['price'];
    String? created_at = item['created_at']; //出价时间
    bool is_raise_price = (item['is_raise_price'] ?? false);

    DateTime now = DateTime.now();
    String date = formatDate(created_at);
    DateTime? created_at_time = DateUtil.getDateTime(date, isUtc: false);
    String str = caculateTime(created_at_time, now);
    Widget widget;

    if (item == null) {
      widget = Container();
    } else {
      widget = Consumer<UserProvider>(builder: (context, provider, child) {
        Map? map = provider.user;
        bool mi = map!['id'].toString() == id;
        String? avatar = photo;
        ImageProvider imageProvider;

        if (["", null].contains(avatar)) {
          imageProvider = AssetImage('images/lt_user/user_placeholder.png');
        } else {
          imageProvider = NetworkImage(avatar as String);
        }
        return Container(
          alignment: Alignment.center,
          height: 80.w,
          width: 350.w,
          decoration: BoxDecoration(
            color: Color(0xffF9F9F9),
          ),
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          margin: EdgeInsets.only(top: 10.w),
          child: Row(
            children: [
              Stack(
                children: [
                  Container(
                    decoration:
                        BoxDecoration(borderRadius: GetRadius.all(20.w)),
                    clipBehavior: Clip.hardEdge,
                    child: Image(
                      image: imageProvider,
                      width: 40.w,
                      height: 40.w,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: Image(
                      image: AssetImage('images/lt_user/level/level_${level}.png'),
                      width: 26.w,
                      height: 14.w,
                    ),
                  ),
                ],
              ),
              HEmptyView(8.w),
              Expanded(
                flex: 1,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Container(
                            child: Text(
                              "${name ?? ""}",
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: ColorConf.normal,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                            constraints:
                                BoxConstraints(maxWidth: Get.width * 0.6),
                          ),
                        ),
                        Row(
                          children: [
                            if (is_raise_price)
                              RoucesUtil.getAssetsIcon('ic_add_price_lt', 16),
                            SizedBox(
                              width: 7.w,
                            ),
                            renderPrice(donePrice, price, mi),
                          ],
                        ),
                        HEmptyView(6.w),
                        buildRightWidget(),
                      ],
                    ),
                    VEmptyView(8.w),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "无效率${NumUtil.multiply(double.tryParse(rate_of_invalid_tenders ?? "0") ?? 0, 100)}%",
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: ColorConf.lightGray,
                          ),
                        ),
                        Text(
                          "$str",
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: UIConstant.color99,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      });
    }
    return widget;
  }

  buildRightWidget() {
    if (index == 0 &&
        ['waitconfirm', 'onsale', 'sold', 'finished', 'wait_pay']
            .contains(status)) {
      //中标
      return Image(
        image: AssetImage(
          'images/lt_backflows/ic_comment_sure.png',
        ),
        height: 18.w,
        width: 32.w,
      );
    } else if (!checkValid()) {
      //无效标
      return Image(
        image: AssetImage(
          'images/lt_backflows/ic_comment_invalid.png',
        ),
        height: 18.w,
        width: 32.w,
      );
    }
    return Container();
  }
}
